package com.tools.cleanmaster.functionpage;


import android.content.Context;
import android.os.Handler;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.nineoldandroids.animation.Animator;
import com.tools.ad.EntranceType;
import com.tools.ad.util.GARecordUtils;
import com.tools.cleanmaster.BuildConfig;
import com.tools.cleanmaster.CleanApplication;
import com.tools.cleanmaster.CleanGAConstant;
import com.tools.cleanmaster.R;
import com.tools.cleanmaster.cpucool.util.PhoneAccelerateHelper;
import com.tools.cleanmaster.scenenew.SceneToolkit;
import com.tools.cleanmaster.taskmain.ProcessItem;
import com.tools.cleanmaster.taskmain.TKPubApi;
import com.tools.cleanmaster.ui.view.functionpage.AppsIconListView;
import com.tools.cleanmaster.utils.MemoryUtils;

import java.util.ArrayList;
import java.util.Locale;
import java.util.Random;

/**
 * 占用内存过高处理类
 */
public class FunctionBoosterHandler extends FunctionHandler {
    private ScanMemoryView boosterScanView;
    private TextView boosterNotification;
    private AppsIconListView appsList;
    private ArrayList<ProcessItem> mList;
    private ImageView mListViewTopImage;

    @Override
    public void init(Context context, View viewRoot) {
        super.init(context, viewRoot);
        boosterScanView = mViewRoot.findViewById(R.id.booster_scan);
        boosterNotification = mViewRoot.findViewById(R.id.function_booster_notification);
        appsList = mViewRoot.findViewById(R.id.run_app_backview);
        mListViewTopImage = mViewRoot.findViewById(R.id.function_battery_top_bg);

        GridView mGridView = mViewRoot.findViewById(R.id.app_icon_grid);
        mGridView.setVerticalFadingEdgeEnabled(true);
        mGridView.setFadingEdgeLength((int) imContext.getResources().getDimension(R.dimen.cpu_icon_list_fading_edge));
    }

    @Override
    public void startStateScan() {
        if (handlerListener != null) {
            handlerListener.startScan();
        }

        mList = TKPubApi.getRunningProcesses(imContext, true);

        mViewRoot.setVisibility(View.VISIBLE);
        boosterScanView.setVisibility(View.VISIBLE);
        boosterScanView.setProgress(SceneToolkit.calcMemoryUsedPercent());

        final long memerySize = MemoryUtils.getAvailableRam(imContext, mList);
        boosterNotification.setText(imContext.getString(R.string.function_booster_over_msg, memerySize + "MB"));

        boosterScanView.startAccAnim(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animator) {
                super.onAnimationEnd(animator);
                if (mList == null || mList.isEmpty()) {
                    GARecordUtils.report(CleanApplication.getInstance(), CleanGAConstant.C_FUNC, CleanGAConstant.A_SHOW,
                            String.format(Locale.ENGLISH, CleanGAConstant.L_FUNCTION_EMPTY_RESULT, "booster"));

                    imContext.getAdSceneManager().load(EntranceType.HOME_BOOST_INTERSTITIAL);

                    //结果停留2s后，才执行完成动画
                    imContext.handleMobEmptyDelayMessage(R.id.msg_show_complete_view, 2000L);

                    FunctionItemSharedPrefs.setFunctionItemOverHandingTime(imContext, FunctionItem.BOOSTEROVER);
                } else {

                    showMessageTop();
                    appsList.setVisibility(View.VISIBLE);
                    if (mListViewTopImage != null) {
                        mListViewTopImage.setVisibility(View.VISIBLE);
                    }
                    ((TextView) mViewRoot.findViewById(R.id.pull_to_refresh_text)).setText(
                            imContext.getString(R.string.function_booster_overtext, mList.size() + ""));
                    appsList.setAppsIcons(mList);


                    if (handlerListener != null) {
                        handlerListener.finishScan();
                    }
                }
            }
        });
    }

    @Override
    public void startStateHandler() {
        if (handlerListener != null) {
            handlerListener.startHandler(true);
        }
        boosterScanView.startDecAnim(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animator) {
                FunctionItemSharedPrefs.setLastBoosterTime(imContext);
                if (appsList != null) {
                    appsList.setVisibility(View.GONE);
                }
                if (mListViewTopImage != null) {
                    mListViewTopImage.setVisibility(View.GONE);
                }
                if (handlerListener != null) {
                    handlerListener.finishHandler();
                }
                mViewRoot.setVisibility(View.GONE);
            }
        });
        PhoneAccelerateHelper.executeAccelerateTask(imContext, mList);
        appsList.clearAppAnimation(null);

        FunctionItemSharedPrefs.setFunctionItemOverHandingTime(imContext, FunctionItem.BOOSTEROVER);
    }

    @Override
    public void startStateFakeHandler() {
        if (handlerListener != null) {
            handlerListener.startScan();
        }
        mViewRoot.setVisibility(View.VISIBLE);
        boosterNotification.setVisibility(View.GONE);
        boosterScanView.setVisibility(View.VISIBLE);
        int threshold = FunctionItemSharedPrefs.getBoosterThreshold(imContext);
        if (threshold <= 5) {
            threshold = 5;
        }

        imContext.getAdSceneManager().load(EntranceType.HOME_BOOST_INTERSTITIAL);
        FunctionItemSharedPrefs.setFunctionItemOverHandingTime(imContext, FunctionItem.BOOSTEROVER);

        boosterScanView.setProgress(new Random().nextInt(threshold / 2) + threshold / 2);
        boosterScanView.startAccAnim(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animator) {
                super.onAnimationEnd(animator);
                boosterNotification.setText(R.string.function_booster_normal_text);
                showMessageTop();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        boosterScanView.startDecAnim(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(Animator animator) {
                                super.onAnimationEnd(animator);
                                boosterScanView.setVisibility(View.GONE);
                                if (handlerListener != null) {
                                    handlerListener.finishHandler();
                                }
                            }
                        });
                    }
                }, 300);
            }
        });

    }

    private void showMessageTop() {
        Animation fadeIn = AnimationUtils.loadAnimation(imContext, R.anim.battery_sharp_normal_shadein);
        boosterNotification.setVisibility(View.VISIBLE);
        boosterNotification.startAnimation(fadeIn);
    }
}
